package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 没天赋
 * @since 2025-2-28
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryTypeList() {
        //1.在redis中获取类型列表
        String list = stringRedisTemplate.opsForValue().get(RedisConstants.TYPE_LIST_KEY);
        //2.存在，直接返回
        if (StrUtil.isNotBlank(list)) {
            return Result.ok(JSONUtil.toList(list, ShopType.class));
        }
        //3.不存在，从数据库中查询列表数据
        List<ShopType> typeList = query().orderByAsc("sort").list();
        //4.将列表数据存入redis
        stringRedisTemplate.opsForValue().set(RedisConstants.TYPE_LIST_KEY, JSONUtil.toJsonStr(typeList));
        //5.返回列表数据
        return Result.ok(typeList);
    }
}
